package dataAccessLayer.dataBase;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DBManager
{
	private DataSource dataSource;
	private Connection connection;
	private String connectionType;
	
	public DBManager( String connectionType )
	{
		this.connectionType = connectionType;
		
		createConnection();
	}
	
	private void createConnection()
	{
		if(connectionType.equals( ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("connectionType") ))
		{
			try 
			{
				Class.forName(ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("driver"));
				
				String address = ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("address");
				String user = ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("user");
				String password = ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("password");
				
				connection = DriverManager.getConnection(address,user,password);
			} 
			catch (ClassNotFoundException e) 
			{
				e.printStackTrace();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
		else
		{
			InitialContext initialContext;
			Context context;

			try 
			{
				initialContext = new InitialContext();
				context = (Context) initialContext.lookup("java:");
				dataSource = (DataSource) context.lookup(ResourceBundle.getBundle("dataAccessLayer.dataAccess").getString("dataSource"));
				
				connection = dataSource.getConnection();
			}
			catch (NamingException e) 
			{
				e.printStackTrace();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	public Connection getConnection()
	{
		return connection;
	}
}
